﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HumanWorkflow.SemanticModel
{
    public partial class HumanWorkflowSemanticModel
    {
        public HumanWorkflowSemanticModel()
        {
            Transitions = new List<Transition>();
            Steps = new List<Step>();
        }

        public void AddTransition(string fromStepName, string toStepName, string name)
        {
            Transition newTransition = new Transition();
            Step toStep = FindStepByName(toStepName);
            Step fromStep = FindStepByName(fromStepName);

            newTransition.ToStep = toStep;
            newTransition.Name = name;

            ((List<Transition>)toStep.InTransitions).Add(newTransition);
            ((List<Transition>)fromStep.OutTransitions).Add(newTransition);

            ((List<Transition>)Transitions).Add(newTransition);
        }

        public void AddStep(Step step)
        {
            ((List<Step>)Steps).Add(step);
        }

        public Transition FindTransitionByName(string transitionName)
        {
            try
            {
                Transition transition = this.Transitions.Where<Transition>(tr => tr.Name == transitionName).First<Transition>();
                return transition;
            }
            catch (InvalidOperationException)
            {
                throw new Exception("Transition with name " + transitionName + " can not be found.");
            }
        }

        public Step FindStepByName(string stepName)
        {           
            try
            {
                Step step = this.Steps.Where<Step>(s => s.Name == stepName).First<Step>();
                return step;
            }
            catch (InvalidOperationException)
            {
                throw new Exception("Step with name " + stepName +" can not be found.");
            }            
        }

    }
}
